from PIL import ImageGrab,Image
from io import BytesIO
import threading
import time

from ds.GlobalVarable import imageQueue


class ImageGen:
    def __init__(self, name):
        self.name = name
        self.imgThread = None
        self.isThreadRunning = False
        self.i = 0
        self.lock = threading.RLock()

    def call(self, stream):
        imageQueue.put(stream)
        self.i += 1
        self.lock.acquire()
        if imageQueue.qsize() == 50:
            imageQueue.get()
        self.lock.release()
        print(f"the current {self.i} img", imageQueue.qsize())

    def start(self):
        def getStream():
            while True:
                if not self.isThreadRunning:
                    return
                img = ImageGrab.grab()
                buffer = BytesIO()
                img.save(buffer, format='jpeg')
                imgBytes = buffer.getvalue()
                buffer.close()
                self.call(imgBytes)
                # time.sleep(0.3)

        self.imgThread = threading.Thread(target=getStream, name=self.name)
        self.isThreadRunning = True
        self.imgThread.start()

    def stop(self):
        self.isThreadRunning = False

    def isAlive(self):
        return self.imgThread.is_alive()


if __name__ == "__main__":
    t = ImageGen(name="generator stream")
    t.start()
    time.sleep(1)
    # t.stop()
